package com.woniuxy.yygh.hsop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yygh.common.exception.YyghException;
import com.woniuxy.yygh.common.result.ResultCodeEnum;
import com.woniuxy.yygh.hsop.mapper.ScheduleMapper;
import com.woniuxy.yygh.hsop.repository.ScheduleRepository;
import com.woniuxy.yygh.hsop.service.DepartmentService;
import com.woniuxy.yygh.hsop.service.HospitalService;
import com.woniuxy.yygh.hsop.service.ScheduleService;
import com.woniuxy.yygh.model.hosp.BookingRule;
import com.woniuxy.yygh.model.hosp.Department;
import com.woniuxy.yygh.model.hosp.Hospital;
import com.woniuxy.yygh.model.hosp.Schedule;
import com.woniuxy.yygh.vo.hosp.BookingScheduleRuleVo;
import com.woniuxy.yygh.vo.hosp.ScheduleOrderVo;
import com.woniuxy.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.awt.print.Book;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 排班信息实现类
 * <P> Date: 2022/3/1:21:09
 * <P> Description:
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule>
        implements ScheduleService {

    /**
     * TODO 操作排班的mongdb
     */
    @Autowired
    private ScheduleRepository scheduleRepository;

    /**
     * TODO 操作排班的mongdb
     */
    @Autowired
    private MongoTemplate mongoTemplate;

    //医院接口
    @Autowired
    private HospitalService hospitalService;

    //科室接口
    @Autowired
    private DepartmentService departmentService;

    /**
     * TODO:上传排班信息
     **/
    @Override
    public void save(Map<String, Object> parameterMap) {
        //map转为 Department 对象
        String mapString = JSONObject.toJSONString(parameterMap);
        Schedule schedule = JSONObject.parseObject(mapString, Schedule.class);

        //判断是否存在相同数据
        String hoscode = schedule.getHoscode();
        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(
                schedule.getHoscode(), schedule.getHosScheduleId());


        //如果存在则更新
        if (scheduleExist != null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setStatus(1);
            scheduleExist.setIsDeleted(0);
            scheduleRepository.save(scheduleExist);

        } else {
            //如果不存在 添加
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }

    /**
     * TODO:分页查找排班的信息
     **/
    @Override
    public Page<Schedule> findPageSchedule(Integer page, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        //创建 Pageable 分页对象
        Pageable pageable = PageRequest.of(page - 1, limit);

        Schedule schedule = new Schedule();
        //设置查询对象的状态 查没有删除和状态为1的
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        //Example对象 条件
        // StringMatcher.CONTAINING 模糊查询 不区分大小写
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, matcher);

        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    /**
     * TODO:根据医院编号和排班编号删除排班
     **/
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        // 医院编号和排班编号  查询
        Schedule schedule = scheduleRepository
                .getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * TODO:医院编号和科室编号 查询排班规则数据
     **/
    @Override
    public Map<String, Object> getRuleSchedule(Integer page, Integer limit, String hoscode, String depcode) {
        // 1.根据医院编号 和 科室编号进行查询
        Criteria criteria = Criteria
                .where("hoscode").is(hoscode).
                and("depcode").is(depcode);

        //2.根据工作日期workdate日期进行分组
        //	 reservedNumber 可预约数
        //	 availableNumber 剩余预约数;
        Aggregation agg = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //根据工作日期分组
                Aggregation.group("workDate")
                        //as 起别名
                        .first("workDate").as("workDate")

                        //3. 统计号源数量
                        .count().as("docCount")
                        // 统计可预约数和剩余预约数的各自的数量
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),

                //根据日期排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),

                //4.实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        //查询数据 查询条件 查询对应的类  返回封装的类
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //分组
                Aggregation.group("workDate")
        );

        //调用方法  返回对象 获得规则的条数
        AggregationResults<BookingScheduleRuleVo> totalResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalResults.getMappedResults().size();

        //获取当前日期周几
        for (BookingScheduleRuleVo scheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = scheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            scheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置数据 进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);
        result.put("total", total);

        //获取医院的名称
        String hosName = hospitalService.getHospName(hoscode);

        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * TODO: 根据 医院编号 和 科室编号 工作日期 查询排班信息
     **/
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 查询mongdb 获得排班 list  医院编号 科室编号 工作日期
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate
                (hoscode, depcode, new DateTime(workDate).toDateTime());

        //list遍历 设置 医院名称 科室名称 日期和d对应星期
        scheduleList.forEach(this::packageSchedule);

        return scheduleList;
    }

    /**
     * TODO:根据医院编号和科室编号 获取可预约的排班数据
     **/
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //封装对象
        HashMap<String, Object> result = new HashMap<>();

        //TODO:通过医院编号 获取医院的预约规则
        //先得到对象
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //获取医院规则
        BookingRule bookingRule = hospital.getBookingRule();

        //TODO:获取可预约日期的数据(分页)
        IPage iPage = this.getListDate(page, limit, bookingRule);

        //获得当前可用预约的日期
        List<Date> dateList = iPage.getRecords();

        //TODO 获取可预约日期里面科室的剩余预约数量

        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                //查询可预约日期的所有科室
                .and("workDate").in(dateList);

        Aggregation agg = Aggregation.newAggregation(
                //查询条件
                Aggregation.match(criteria),
                //根据日期分组
                Aggregation.group("workDate").first("workDate").as("workDate")
                        //统计
                        .count().as("docCount")
                        //预约数量求和 reservedNumber 可预约数
                        .sum("availableNumber").as("availableNumber")
                        //统计剩余预约数
                        .sum("reservedNumber").as("reservedNumber")
        );

        AggregationResults<BookingScheduleRuleVo> aggregateResult =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);


        List<BookingScheduleRuleVo> scheduleVoList = aggregateResult.getMappedResults();

        //TODO 合并数据 map集合 key为日期 value为预约规则和 剩余数量等
        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().
                    //转成map 可以为日期 value 为预约规则
                            collect(
                            Collectors.toMap(
                                    BookingScheduleRuleVo::getWorkDate,
                                    BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        //TODO 循环日期 获取可预约排版规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            //从map从日期key获得value
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);

            //TODO 如果当前对象为空 说明当天没有排班的医生 设置返回状态
            if (bookingScheduleRuleVo == null) {

                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //TODO 设置返回值
            //可预约日期
            //年月日
            bookingScheduleRuleVo.setWorkDate(date);
            //月日
            bookingScheduleRuleVo.setWorkDateMd(date);

            //计算当前预约日 对应 星期几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //TODO 最后一页 最后一条记录为即将预约
            //TODO 设置状态 0:为正常 1:即将放号 -1:当天已经停止发号了
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }

            //如果当天预约过了停号时间  不能预约
            if (i == 0 && page == 1) {
                DateTime dateTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (dateTime.isBeforeNow()) {
                    //TODO 设置为停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());

        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();

        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));

        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);

        //大科室名称
        baseMap.put("bigname", department.getBigname());

        //科室名称
        baseMap.put("depname", department.getDepname());

        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));

        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());

        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());

        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * TODO:获取排班id 获得排班的数据
     **/
    @Override
    public Schedule getScheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        //封装返回
        return this.packageSchedule(schedule);
    }

    /**
     * TODO:根据排班id获取预约下单数据
     **/
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //对象封装
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //  System.out.println(scheduleId);
        Schedule schedule = mongoTemplate.findById(scheduleId, Schedule.class);
        // System.out.println(schedule);


        //获取排版信息
        //Schedule schedule = baseMapper.selectById(scheduleId);
        if (schedule == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //获取预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        BookingRule bookingRule = hospital.getBookingRule();

        if (bookingRule == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        //把数据设置到 scheduleOrderVo 中
        //TODO 医院编号 和 医院名称
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));

        //TODO 科室编号和科室名称
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));

        //TODO 排班编号
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        //TODO 可预约数量
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        //TODO 剩余预约数
        scheduleOrderVo.setReservedNumber(schedule.getReservedNumber());

        //TODO 医生职称
        scheduleOrderVo.setTitle(schedule.getTitle());
        //TODO 安排日期
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        //TODO 安排时间（0:上午 1:下午）
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        //TODO 医事服务费
        scheduleOrderVo.setAmount(schedule.getAmount());


        //TODO 退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //TODO 预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //TODO 预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //TODO 当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(startTime.toDate());
        // System.out.println("返回的对象" + scheduleOrderVo);
        return scheduleOrderVo;
    }


    /**
     * TODO:更新排班信息 用于MQ操作
     **/
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        System.out.println("mq被调用");
        scheduleRepository.save(schedule);
    }

    /**
     * TODO:获取可预约日期的分页数据
     **/
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //  TODO 获取当天的放号时间  包含年月日小时分钟
        //放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        //TODO 获取预约周期 可以提前预约多久
        Integer cycle = bookingRule.getCycle();

        //TODO 如果当天放号时间过去了 预约周期从后一天开始计算 周期+1
        //和 现在的时间进行比较 如果已经超过这个放号时间  则返回true
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }

        //TODO 获取可预约的所有日期  最后一天显示即将放号
        ArrayList<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime currentTime = new DateTime().plusDays(i);//当天周期加1
            String dataString = currentTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dataString).toDate());
        }

        //TODO 预约周期不同 每页显示日期 最多显示7天数据 如果超过7天 需要做分页
        ArrayList<Date> pageDataList = new ArrayList<>();
        //1-1 * 7   =0
        int start = (page - 1) * limit;
        //1*1 * 7 + 1  =7
        int end = (page - 1) * limit + limit;

        //TODO 如果显示数据小于7 直接显示 获取当前list的长度即可 表示显示多少天
        if (end > dateList.size()) {
            end = dateList.size();

        }
        //TODO 把数据放到分页中 最多显示7条数据
        for (int i = start; i < end; i++) {
            pageDataList.add(dateList.get(i));
        }

        //如果显示数据大于 7 进行分页
        IPage<Date> iPage =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, dateList.size());
        iPage.setRecords(pageDataList);


        return iPage;
    }

    /**
     * TODO:将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     **/
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    /**
     * TODO: 封装排班的 医院名称 科室名称 日期和d对应星期
     **/
    private Schedule packageSchedule(Schedule schedule) {
        schedule.getParam().put("hosname", hospitalService.getHospName(schedule.getHoscode()));
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));

        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",
                this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    /**
     * TODO:工具类 传入日期 内部返回知类枚举 返回当前周几
     **/
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
